<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
</head>

<body>
<input type="file" id="fileInput">
<button id="uploadButton">Upload</button>
<div id="progressBar" style="width: 300px; height: 20px; border: 1px solid #000;">
    <div id="progress" style="width: 0%; height: 100%; background-color: #00ff00;"></div>
</div>

<script>
    const fileInput = document.getElementById('fileInput');
    const uploadButton = document.getElementById('uploadButton');
    const progressBar = document.getElementById('progress');

    uploadButton.addEventListener('click', async () => {
        const file = fileInput.files[0];
        if (!file) {
            alert('Please select a file.');
            return;
        }
        const chunkSize = 1024 * 1024; // 1MB
        const totalChunks = Math.ceil(file.size / chunkSize);
        //const hash = await calculateFileHash(file);
        const hash = Date.now().toString();

        console.log('hash',hash)
        console.log('totalChunks',totalChunks)

        let uploadedChunks = 0;
        const uploadPromises = [];

        for (let i = 0; i < totalChunks; i++) {
            const start = i * chunkSize;
            const end = Math.min(start + chunkSize, file.size);
            const chunk = file.slice(start, end);

            const uploadPromise = uploadChunk(chunk, file.name, i, totalChunks, hash);
            uploadPromises.push(uploadPromise);

            uploadPromise.then(() => {
                uploadedChunks++;
                const progress = (uploadedChunks / totalChunks) * 100;
                progressBar.style.width = `${progress}%`;
                progressBar.innerText = `${progress}%`;
                console.log('progress',progress)
            }).catch((error) => {
                console.error(`Error uploading chunk ${i}:`, error);
                // 错误重试
                uploadChunk(chunk, file.name, i, totalChunks, hash).then(() => {
                    uploadedChunks++;
                    const progress = (uploadedChunks / totalChunks) * 100;
                    progressBar.style.width = `${progress}%`;
                    progressBar.innerText = `${progress}%`;
                    console.log('err.progress',progress)
                }).catch((retryError) => {
                    console.error(`Failed to retry uploading chunk ${i}:`, retryError);
                });
            });
        }

        await Promise.all(uploadPromises);
        alert('File uploaded successfully.');
    });

    async function calculateFileHash(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsArrayBuffer(file);

            reader.onload = async () => {
                try {
                    const buffer = reader.result;
                    const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
                    const hashArray = Array.from(new Uint8Array(hashBuffer));
                    const hashHex = hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('');
                    resolve(hashHex);
                } catch (error) {
                    reject(error);
                }
            };

            reader.onerror = () => {
                reject(reader.error);
            };
        });
    }

    async function uploadChunk(chunk, fileName, chunkIndex, totalChunks, hash) {
        // const formData = new FormData();
        // formData.append('chunk', chunk);

        const response = await fetch('/upload', {
            method: 'POST',
            headers: {
                'X-File-Name': fileName,
                'X-Chunk-Index': chunkIndex,
                'X-Total-Chunks': totalChunks,
                'X-File-Hash': hash
            },
            body: chunk
        });

        if (!response.ok) {
            throw new Error(`Upload failed with status ${response.status}`);
        }
    }
</script>
</body>

</html>
